import React, { Children, useContext, useState } from "react";
import classNames from 'classnames'
import { MenuContext } from './menu'
import { MenuItemProps } from './menuItem'

export interface SubMenuProps {
  index?: string;
  title: string;
  className?: string
  children?: React.ReactNode
} 

const SubMenu: React.FC<SubMenuProps> = (props: SubMenuProps) => {
  const { index, title, className, children } = props
  // set default open menu
  const context = useContext(MenuContext) 
  const openSubMenus = context.defaultOpenSubMenus as Array<string>
  const isOpen = (index && context.mode === 'vertical') ? openSubMenus.includes(index) : false
  const [menuOpen, setMenuOpen] = useState(isOpen)
  const classes = classNames('submenu', className, {
    'menu-opened': menuOpen
  })
  // vertical mode bind click event to set class menu-opened
  const clickEvents = context.mode === 'vertical' ? {
    onClick: () => {
      setMenuOpen(!menuOpen)
    }
  } : {}
  let timer:any
  const handleMouse = (e: React.MouseEvent, isOpen: boolean) => {
    clearTimeout(timer)
    timer = setTimeout(() => {
      setMenuOpen(isOpen)
    }, 300)
  }
  // horizontal mode bind mouse event to set class menu-opened
  const mouseEvents = context.mode === 'horizontal' ? {
    onMouseEnter: (e: React.MouseEvent) => handleMouse(e, true),
    onMouseLeave: (e: React.MouseEvent) => handleMouse(e, false),
  } : {}
  // render menuItem component
  const renderChild = React.Children.map(children, (child, i) => {
    const childElement = child as React.FunctionComponentElement<MenuItemProps>
    const { displayName } = childElement.type
    if((displayName === 'menuItem' || displayName === 'subMenu') && index) {
      // add the subMenu's menuItem a prop index, like 3-1 3-2
      return React.cloneElement(childElement, { index: `${index}-${i}` })
    } else {
      // when the children is not menuItem
      console.log('warn: subMenu has a child which is not a MenuItem component')
    }
  })
  
  return (
    <li className='submenu-item menu-item' {...mouseEvents}>
      <div className="submenu-title" {...clickEvents}>
        {title}
      </div>
      <ul className={classes}>
       {renderChild}
      </ul>
    </li>
  )
}

SubMenu.displayName = 'subMenu'

export default SubMenu
